/*
 * @Author: '421666927@qq.com' '421666927@qq.com'
 * @Date: 2024-08-07 20:14:20
 * @LastEditors: '421666927@qq.com' '421666927@qq.com'
 * @LastEditTime: 2024-08-08 11:35:40
 * @FilePath: \yy-screen-adapter\src\App.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  useState,
  useEffect,
  memo,
  JSXElementConstructor,
  ReactElement,
  ReactNode,
  ReactPortal,
  CSSProperties,
} from "react";

export const ScreenAdapter = memo(
  (props: {
    width: number;
    height: number;
    children:
      | string
      | number
      | boolean
      | ReactElement<any, string | JSXElementConstructor<any>>
      | Iterable<ReactNode>
      | ReactPortal
      | null
      | undefined;
  }) => {
    const [style, setStyle] = useState<CSSProperties>({
      width: props.width + "px",
      height: props.height + "px",
      top: "50%",
      left: "50%",
      transition: ".3s",
      transformOrigin: "0 0",
      position: "absolute",
      transform: "scale(1) translate(-50%, -50%)",
    });
    // 节流 定时器 + 时间戳
    const throttle = (func: any, delay: number = 50) => {
      // 第一次触发时间戳
      let startTime = Date.now();
      return (...args: any[]) => {
        // 如果不是剪头函数可以使用arguments获取参数，这样就不用写形参了考虑形参个数了
        // let args = arguments;
        // 再次触发时间
        const curTime = Date.now();
        // 间隔时间 = 延迟的时间 - （再次触发时间戳 - 第一次触发时间戳）
        const interval = delay - (curTime - startTime);
        if (interval <= 0) {
          // 重新计算开始时间
          startTime = Date.now();
          return func(...args);
        }
      };
    };

    const setScale = () => {
      setStyle({
        ...style,
        transform: "scale(" + getScale() + ") translate(-50%, -50%)",
      });
    };
    const getScale = () => {
      const w = window.innerWidth / props.width;
      const h = window.innerHeight / props.height;
      return w < h ? w : h;
    };
    const resizeFn = () => {
      throttle(setScale());
    };
    useEffect(() => {
      window.addEventListener("resize", resizeFn);
      setScale();
      return () => {
        window.removeEventListener("resize", resizeFn);
      };
    }, []);

    return (
      <div className="ScreenAdapter"  style={style}>
        {props.children}
      </div>
    );
  }
);
